
#! /usr/bin/python

import sys
import os
import time
#sys.path.append('..'+os.sep+'trunk')
sys.path.append('../../../')
from spade import *
class Example(Agent.Agent):
    def _setup(self):
        entry = "Starting Organization Behaviour"




    def _process(self):
	 time.sleep(2000)
class MyOrganization(Federation.Federation):
    def _process(self):
        time.sleep(2000)



class MyUnit(Unit.Hierarchy):
    def _process(self):
        self.setGoal({"necesita":"fuentes de reservas","ofrece":"reservas a resturantes"})
        time.sleep(300)
        m=self.getMemberList()
        print m


    def creationPermissionTest(self,sender,desc=None):
       return False
    def entryUnitTest(self,sender,desc=None):
      print desc
      d=desc
      if d.has_key("ofrece"):
           if str(d["ofrece"])=="fuentes de reservas":
               return True
      return False
    def askMembers(self,about):
        members=self.getMemberList()
        for m in members:
            mens=ACLMessage.ACLMessage()
            mens.setPerformative("request")
            mens.setSender(self.myAgent.getAID())
            aid=AID.aid(m,["xmpp://"+m])
            mens.addReceiver(aid)
            mens.setOntology("Restaurant")
            mens.setContent(about)
            print "Solicitamos"+str(mens)
            self.sendPrivateMessage(i,m)
        time.sleep(100)
        mens=self.receiveMessage()
        while mens:
            print "Recibimos"
            mens
            mens=self.receiveMessage()

class MyUnit2(Unit.Team):
    def _process(self):
        #self.setGoal({"necesita":"fuentes de informacion"})
        time.sleep(300)


if __name__ == "__main__":
    agent = "greservas@apolo.dsic.upv.es"
    #agent = "agent@thx1138.dsic.upv.es"
    #agent = "agent@tatooine.dsic.upv.es"

    b = Example(agent,"pasword")
    b.start()
    print "Agent "+agent+" registering"

    lista= b.getOrganizationList()
    print lista
    for i in lista:
        info=b.getOrganizationInfo(i)
        if info.has_key("goal"):
            goal=info["goal"]
            g=eval(goal)
            print info
            if g.has_key("ofrece") and "reservas a resturantes" in g["ofrece"]:
                o=MyOrganization(b,nick="gReservas", name=i)
                b.joinOrganization(o)
                try:
                    u=MyUnit(agent=b, nick="supervisor", name="reservas",password="pass2")
                    o.addUnit(u)
                except Exception,e:
                    r=o.requestSupervision({"rol":"supervision","ofrece":"reservas a resturantes"})
                    if r:
                        o.addUnit(u)
                        team=MyUnit2(agent=b, nick="reservas",name="eoe",password="pass")
                        o.joinSupervisorTeam(team)
                        ans=team.receiveMessage()
                        while not ans:
                            ans=team.receiveMessage()
                        print ans
                        member=u.getMemberList()
                        for m in member:
                            mens=ACLMessage.ACLMessage()
                            mens.setPerformative("request")
                            mens.setSender(b.getAID())
                            aid=AID.aid(m,["xmpp://"+m])
                            mens.addReceiver(aid)
                            mens.setOntology("Restaurant:reserva")
                            mens.setContent(ans.getContent())
                            print mens
                            u.sendPrivateMessage(mens,m)
                        time.sleep(10)
                        list=[]
                        ans=u.receiveMessage()
                        while ans:
                            print ans
                            if ans.getPerformative()=="inform":
                                d={"jid":str(ans.getSender().getName()),"info":str(ans.getContent())}
                                list=list+[d]
                            ans=u.receiveMessage()
                        mens=ACLMessage.ACLMessage()
                        mens.setPerformative("inform")
                        mens.setSender(b.getAID())
                        mens.addReceiver(b.getAID())
                        mens.setOntology("Restaurant:reserva")
                        mens.setContent(str(list))
                        print mens
                        team.sendMessage(mens)




